package com.resolution.dietaryassessment.view.mydietary;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.rxbus.RxBus;
import com.example.rxbus.bean.MsgEvent;
import com.resolution.dietaryassessment.BaseActivity;
import com.resolution.dietaryassessment.R;
import com.resolution.dietaryassessment.utils.JumpTextWatcher;
import com.resolution.dietaryassessment.view.main.MainActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * @author By Resolusion
 * @Title: MyDietaryActivity
 * 我的饮食合理吗
 * @Date: 2020/1/8
 * @Time: 13:36
 * @email res01ution@foxmail.com
 */
public class MyDietaryActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener{

    private static final String TAG = "...." ;
    @BindView(R.id.name_etx)
    TextView nameEtx;
    @BindView(R.id.age_etx)
    EditText ageEtx;
    @BindView(R.id.height_etx)
    EditText heightEtx;
    @BindView(R.id.weight_etx)
    EditText weightEtx;
    @BindView(R.id.man_radio)
    RadioButton manRadio;
    @BindView(R.id.woman_radio)
    RadioButton womanRadio;
    @BindView(R.id.very_mild_radio)
    RadioButton veryMildRadio;
    @BindView(R.id.mild_radio)
    RadioButton mildRadio;
    @BindView(R.id.medium_radio)
    RadioButton mediumRadio;
    @BindView(R.id.severe_radio)
    RadioButton severeRadio;
    @BindView(R.id.num1)
    Button num1;
    @BindView(R.id.num2)
    Button num2;
    @BindView(R.id.num3)
    Button num3;
    @BindView(R.id.num4)
    Button num4;
    @BindView(R.id.num5)
    Button num5;
    @BindView(R.id.num6)
    Button num6;
    @BindView(R.id.num7)
    Button num7;
    @BindView(R.id.num8)
    Button num8;
    @BindView(R.id.num9)
    Button num9;
    @BindView(R.id.num0)
    Button num0;
    @BindView(R.id.num_point)
    Button numPoint;
    @BindView(R.id.sure)
    Button sure;
    @BindView(R.id.reset)
    Button reset;
    @BindView(R.id.delete)
    Button delete;

    @BindView(R.id.next_btn)
    Button btn_next;
    @BindView(R.id.re_fanhui_btn)
    Button btn_return;
    @BindView(R.id.leave_btn)
    Button btn_leave;

    @BindView(R.id.tip)
    TextView tip;
    @BindView(R.id.radio1)
    RadioButton radio1;
    @BindView(R.id.radio2)
    RadioButton radio2;
    @BindView(R.id.radio3)
    RadioButton radio3;
    @BindView(R.id.radio4)
    RadioButton radio4;


    RadioGroup choiceRadioGroup;
    RadioGroup normalRadioGroup;
    RadioGroup sexRadioGroup;

    String str1="";

    List<EditText> editTexts = new ArrayList<>();
    JumpTextWatcher ageWatcher,heightWatcher,weightWatcher;

    private int age = 0;
    private float height = 0;
    private float weight = 0;
    private int sex = MAN;
    private int motionIndex = MILDER;

    //蛋白质，脂肪，碳水
    private int protein;
    private int fat;
    private int carbon;
    private int mReLiang;

    //性别status
    public final static int MAN = 1;
    public final static int WOMAN = 2;

    //运动指数status
    public final static int MILDER = 1;
    public final static int MILD = 2;
    public final static int MEDIUM = 3;
    public final static int SEVERE = 4;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_dietary);
        ButterKnife.bind(this);
        Collections.addAll(editTexts,ageEtx,heightEtx,weightEtx);
        initView();
    }

    public void initView() {
        //为EditText添加监听器
        ageWatcher = new JumpTextWatcher(ageEtx,heightEtx,sure);
        heightWatcher = new JumpTextWatcher(heightEtx,weightEtx,sure);
        weightWatcher = new JumpTextWatcher(weightEtx,ageEtx,sure);

        ageEtx.addTextChangedListener(ageWatcher);
        heightEtx.addTextChangedListener(heightWatcher);
        weightEtx.addTextChangedListener(weightWatcher);

        //radioButton联动
        choiceRadioGroup = findViewById(R.id.choice_group);
        normalRadioGroup = findViewById(R.id.normal_group);
        sexRadioGroup  = findViewById(R.id.sex_rg);

        choiceRadioGroup.setOnCheckedChangeListener(this);
        sexRadioGroup.setOnCheckedChangeListener(this);
        for (int i = 0;i < normalRadioGroup.getChildCount(); i++) {
            normalRadioGroup.getChildAt(i).setEnabled(false);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.man_radio :
                sex = MAN;
                break;
            case R.id.woman_radio :
                sex = WOMAN;
                break;
            case R.id.very_mild_radio:
                radio1.setChecked(true);
                motionIndex = MILDER;
                break;
            case R.id.mild_radio:
                radio2.setChecked(true);
                motionIndex = MILD;
                break;
            case R.id.medium_radio:
                radio3.setChecked(true);
                motionIndex = MEDIUM;
                break;
            case R.id.severe_radio:
                radio4.setChecked(true);
                motionIndex = SEVERE;
                break;
        }
    }

    @OnClick({R.id.num1, R.id.num2, R.id.num3, R.id.num4, R.id.num5, R.id.num6, R.id.num7,
            R.id.num8, R.id.num9, R.id.num0, R.id.num_point, R.id.reset, R.id.delete,R.id.next_btn,
            R.id.re_fanhui_btn,R.id.leave_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.num1:
            case R.id.num2:
            case R.id.num3:
            case R.id.num4:
            case R.id.num5:
            case R.id.num6:
            case R.id.num7:
            case R.id.num8:
            case R.id.num9:
            case R.id.num0:
            case R.id.num_point:
                for (EditText e : editTexts){
                    str1 = e.getText().toString() + ((Button)view).getText().toString();
                    if (e.hasFocus()) {
                        e.setText(str1);
                        e.setSelection(e.getText().length());
                    }
                }
                break;
            case R.id.reset:
                for (EditText e : editTexts){
                    if (e.isFocused()){
                        e.setText("");
                    }
                }
                break;
            case R.id.delete:
                for (EditText e : editTexts){
                    if (e.isFocused()){
                        int keyCode = KeyEvent.KEYCODE_DEL;
                        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
                        e.dispatchKeyEvent(keyEvent);
                    }
                }
                break;
            case R.id.next_btn:
                if (InputInspect()){
                    Intent intent = new Intent(this,FragHolderActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("蛋白质",protein);
                    bundle.putInt("脂肪",fat);
                    bundle.putInt("碳水",carbon);
                    bundle.putInt("热量",mReLiang);
                    intent.putExtra("info",bundle);
                    startActivity(intent);
                }
                break;
            case R.id.re_fanhui_btn:
            case R.id.leave_btn:
                start(MainActivity.class);
                break;
            default:
        }
    }

    /**
     * 输入检查
     */
    private boolean InputInspect(){
        if (ageEtx.getText().length() == 0 || heightEtx.getText().length() == 0
                ||weightEtx.getText().length() == 0){
            Toasty.Config.getInstance()
                    .allowQueue(false)
                    .setTextSize(12)
                    .apply();
            Toasty.error(this,"您的基本信息不完整").show();
            return false;
        }else if (!isInteger(ageEtx.getText().toString())) {
            Toasty.warning(this,"请输入正确的年龄信息").show();
            return false;
        }
        Log.d(TAG, "InputInspect: " + Integer.parseInt(ageEtx.getText().toString()));
        getUserInfo();
        return true;
    }

    /**
     * 获取用户基本信息
     */
    private void getUserInfo(){
        age = Integer.parseInt(ageEtx.getText().toString());
        height = Float.parseFloat(heightEtx.getText().toString());
        weight = Float.parseFloat(weightEtx.getText().toString());

        CalculationNutrition(CalculationHead(sex,motionIndex));
    }

    /**
     * 判断字符串是否是整数
     */
    private static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 计算每日所需热量
     * 男人: [66 + (13.7 * weight) + (5 * height) - (6.8 * age)] * motionIndex * 1.1
     * 女人: [655 + (9.6 * weight) + (1.8 * height) - (4.7 * age)] * motionIndex * 1.1
     * 食物消化所需能量，约为10%
     */
    private int CalculationHead(int sex,int status){
        int mResult;
        float mQuantity = 0;
        if (sex == MAN){
            mQuantity = (float) (66.0 + (13.7 * weight) + (5 * height) - (6.8 * age));
        }else if (sex == WOMAN){
            mQuantity = (float) (655 + (9.6 * weight) + (1.8 * height) - (4.7 * age));
        }
        switch (status) {
            case MILDER :
                mResult = (int)(mQuantity * 1.2 * 1.1);
                break;
            case MILD:
                mResult = (int)(mQuantity * 1.375 * 1.1);
                break;
            case MEDIUM:
                mResult = (int)(mQuantity * 1.55 * 1.1);
                break;
            case SEVERE:
                mResult = (int)(mQuantity * 1.725 * 1.1);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + status);
        }
        return mResult;
    }

    /**
     * 计算每日所需营养物质
     */
    private void CalculationNutrition(float quantity){
        //蛋白质，脂肪，碳水
        mReLiang = (int)(quantity);
        protein = (int) (quantity * 0.025);
        fat = (int) (0.03875 * quantity);
        carbon = (int) (0.155 * quantity);

        Log.d(TAG, "CalculationNutrition: " + protein +"\n" + fat + "\n" + carbon + "\n" + mReLiang);
        Log.d(TAG, "CalculationNutrition: " + age + "..." + height + "..." + weight + "..." + sex + "..." + motionIndex);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ageEtx.removeTextChangedListener(ageWatcher);
        heightEtx.removeTextChangedListener(heightWatcher);
        weightEtx.removeTextChangedListener(weightWatcher);
        finish();
    }
}